//
//  ZCAreaVC.m
//  ZCJZ
//
//  Created by sujeking on 2019/3/1.
//  Copyright © 2019年 jeking. All rights reserved.
//

#import "ZCAreaVC.h"
#import "ZCAddressViewModel.h"
#import "ZCAreaVCListCell.h"
#import <Masonry.h>
#import "TBCityIconFont.h"

@interface ZCAreaVC ()<UITableViewDelegate,UITableViewDataSource>

@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
@property (nonatomic, strong) UITableView *currentTv;


@property (weak, nonatomic) IBOutlet UIButton *closeBtn;
@property (weak, nonatomic) IBOutlet UIView *tagView;
@property (weak, nonatomic) IBOutlet UIView *tagline;

@property (nonatomic, strong) NSMutableArray *list;
@property (nonatomic, strong) NSMutableArray *selected;
@property (assign, nonatomic) NSInteger currentIndex;

@property (nonatomic, copy) NSArray *prArr;
@property (nonatomic, copy) NSArray *ctArr;
@property (nonatomic, copy) NSArray *arArr;

@property (nonatomic, strong) UIButton *tipBtn;


@end

@implementation ZCAreaVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupUI];
    [self netFetchAreaListWithPid:nil];
}

- (void)setupUI {
    self.currentIndex = 0;
    __weak typeof(self) weakSelf = self;
    self.tipBtn = [self tagBtnWithTitle:@"请选择"];
    self.tipBtn.userInteractionEnabled = NO;
    self.tipBtn.tag = -1;
    [self.tagView addSubview:self.tipBtn];
    [self.tipBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(12);
        make.top.mas_equalTo(0);
        make.bottom.mas_equalTo(weakSelf.tagline.mas_top);
    }];
    
    self.scrollView.contentSize = CGSizeMake([UIScreen mainScreen].bounds.size.width * 3, CGRectGetHeight(self.scrollView.bounds));
    for (NSInteger i = 0; i < 3; i++) {
        UITableView *tv = [self getTableViewWithTag:200 + i];
        if (i == 0) {
            self.currentTv = tv;
        }
        [self.scrollView addSubview:tv];
        [tv mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(i * [UIScreen mainScreen].bounds.size.width);
            make.top.bottom.mas_equalTo(0);
            make.width.mas_equalTo([UIScreen mainScreen].bounds.size.width);
            make.height.mas_equalTo(weakSelf.scrollView.mas_height);
        }];
    }
    
    UIImage *closeimg = [UIImage iconWithInfo:TBCityIconInfoMake(@"\U0000e61e", 20, [generalToolBox getColorWithHexadecimalColorStr:@"0xC20114"])];
    closeimg = [closeimg imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    [self.closeBtn setImage:closeimg forState:UIControlStateNormal];
}

- (void)updateTagView {
    for (UIView *btn in self.tagView.subviews) {
        if (btn.tag >= 300) {
            [btn removeFromSuperview];
        }
    }
    UIButton *lastBtn = nil;
    __weak typeof(self) weakSelf = self;
    for (NSInteger i = 0; i < self.selected.count; i++) {
        NSDictionary *dict = self.selected[i];
        NSString *name = [dict valueForKey:@"name"];
        UIButton *btn = [self tagBtnWithTitle:name];
        btn.tag = 300 + i;
        [self.tagView addSubview:btn];
        [btn mas_makeConstraints:^(MASConstraintMaker *make) {
            if (lastBtn == nil) {
                make.left.mas_equalTo(12);
            } else {
                make.left.mas_equalTo(lastBtn.mas_right).offset(10);
            }
            make.top.mas_equalTo(0);
            make.bottom.mas_equalTo(weakSelf.tagline.mas_top);
        }];
        [self.tagView layoutIfNeeded];
        lastBtn = btn;
    }

    [self.tipBtn mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(lastBtn.mas_right).offset(10);
        make.top.mas_equalTo(0);
        make.bottom.mas_equalTo(weakSelf.tagline.mas_top);
    }];
    
    if (self.selected.count >= 3) {
        self.tipBtn.hidden = YES;
    } else {
        self.tipBtn.hidden = NO;
    }
    
    self.currentIndex += 1;
}

// MARK: - UITableViewDelegate,UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    switch (tableView.tag) {
        case 200:
        {
            return self.prArr.count;
        }
            break;
        case 201:
        {
            return self.ctArr.count;
        }
            break;
        case 202:
        {
            return self.arArr.count;
        }
            break;
        default:
            break;
    }
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSInteger row = indexPath.row;
    ZCAreaVCListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ZCAreaVCListCell"
                                                             forIndexPath:indexPath];
    switch (tableView.tag) {
        case 200:
        {
            NSDictionary *dict = self.prArr[row];
            cell.dict = dict;
        }
            break;
        case 201:
        {
            NSDictionary *dict = self.ctArr[row];
            cell.dict = dict;
            
        }
            break;
        case 202:
        {
            NSDictionary *dict = self.arArr[row];
            cell.dict = dict;
        }
            break;
        default:
            break;
    }
    return cell;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 44.0f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0.01f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.01;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    WeakSelf(self);
    NSInteger row = indexPath.row;
    NSDictionary *dict = nil;
    switch(tableView.tag) {
        case 200:
        {
            dict = self.prArr[row];
            self.ctArr = nil;
            self.arArr = nil;
            [self.selected removeAllObjects];
        }
            break;
        case 201:
        {
            dict = self.ctArr[row];
            self.arArr = nil;
            if (self.selected.count > 2) {
                [self.selected removeObjectsInRange:(NSRange){1,self.selected.count - 1}];
            }
        }
            break;
        case 202:
        {
            dict = self.arArr[row];
        }
            break;
        default:
            break;
    }
    [self.selected addObject:dict];
    [self updateTagView];
    if (self.selected.count == 3) {
        [self dismissViewControllerAnimated:YES completion:^{
            if (weakself.selectedAddressCallBack) {
                weakself.selectedAddressCallBack(weakself.selected);
            }
        }];
    } else {
        [self netFetchAreaListWithPid:[dict valueForKey:@"id"]];
    }
}

// MARK: - Action

- (void)tagBtnClickAction:(UIButton *)sender {
    if (sender.tag == -1) {
        return;
    }
    self.currentIndex = sender.tag - 300;
    [self.scrollView setContentOffset:(CGPoint){[UIScreen mainScreen].bounds.size.width * self.currentIndex,0} animated:YES];
}

- (IBAction)closeBtnClickAction:(id)sender {
    [self dismissViewControllerAnimated:YES completion:nil];
}

// MARK: - NET

- (void)netFetchAreaListWithPid:(NSString *)pid {
    WeakSelf(self);
    if (self.is_pay) {
        
        [ZCAddressViewModel fetchPayAreaListWithPid:pid complete:^(ZCErrorCode status, NSString *message, id data) {
            if (weakself.currentIndex == 0) {
                weakself.prArr = data;
            } else if (weakself.currentIndex == 1) {
                weakself.ctArr = data;
            } else {
                weakself.arArr = data;
            }
            weakself.currentTv = [weakself.scrollView viewWithTag:200 + weakself.currentIndex];
            [weakself.currentTv reloadData];
            [weakself.scrollView setContentOffset:(CGPoint){weakself.currentIndex * [UIScreen mainScreen].bounds.size.width,0} animated:YES];
        }];
    } else {
        
        [ZCAddressViewModel fetchAreaListWithPid:pid complete:^(ZCErrorCode status, NSString *message, id data) {
            if (weakself.currentIndex == 0) {
                weakself.prArr = data;
            } else if (weakself.currentIndex == 1) {
                weakself.ctArr = data;
            } else {
                weakself.arArr = data;
            }
            if ([data isKindOfClass:[NSArray class]] && ((NSArray*)data).count==0) {
                
                [weakself dismissViewControllerAnimated:YES completion:^{
                    if (weakself.selectedAddressCallBack) {
                        weakself.selectedAddressCallBack(weakself.selected);
                    }
                }];
                return;
            }
            weakself.currentTv = [weakself.scrollView viewWithTag:200 + weakself.currentIndex];
            [weakself.currentTv reloadData];
            [weakself.scrollView setContentOffset:(CGPoint){weakself.currentIndex * [UIScreen mainScreen].bounds.size.width,0} animated:YES];
        }];
    }
    
}

// MARK: - GET

- (UIButton *)tagBtnWithTitle:(NSString *)title {
    UIButton *btn = [UIButton new];
    [btn setTitleColor:UIColorFromRGB(0x333333) forState:UIControlStateNormal];
    [btn setTitleColor:UIColorFromRGB(0xDF2C3F) forState:UIControlStateSelected];
    [btn setTitle:title forState:UIControlStateNormal];
    btn.titleLabel.font = [UIFont systemFontOfSize:15];
    [btn addTarget:self action:@selector(tagBtnClickAction:) forControlEvents:UIControlEventTouchUpInside];
    return btn;
}

- (NSMutableArray *)list {
    if (_list == nil) {
        _list = [NSMutableArray new];
    }
    return _list;
}

- (NSMutableArray *)selected {
    if (_selected == nil) {
        _selected = @[].mutableCopy;
    }
    return _selected;
}

- (UITableView *)getTableViewWithTag:(NSInteger)tag {
    UITableView *tv = [UITableView new];
    tv.dataSource = self;
    tv.delegate = self;
    tv.tag = tag;
    [tv registerNib:[UINib nibWithNibName:@"ZCAreaVCListCell" bundle:nil]
forCellReuseIdentifier:@"ZCAreaVCListCell"];
    
    return tv;
}

- (NSArray *)prArr {
    if (_prArr == nil) {
        _prArr = @[];
    }
    return _prArr;
}
- (NSArray *)ctArr {
    if (_ctArr == nil) {
        _ctArr = @[];
    }
    return _ctArr;
}
- (NSArray *)arArr {
    if (_arArr == nil) {
        _arArr = @[];
    }
    return _arArr;
}

- (void)dealloc{
    NSLog(@"dealloc==========");
}

@end
